package com.music.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.music.dao.*;
import com.music.entity.*;
import com.music.service.CommentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
@Transactional
public class CommentServiceImpl implements CommentService {
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private SingerMapper singerMapper;
    @Autowired
    private AlbumMapper albumMapper;
    @Autowired
    private GenresMapper genresMapper;
    @Autowired
    private CommentLikeMapper commentLikeMapper;

    @Override
    public PageInfo<Comment> getCommentByPage(int pageNum, int pageSize, Comment comment, boolean time) {

//        1、开始分页，获取pageNum页的pageSize条，默认统计记录数
        PageHelper.startPage(pageNum,pageSize);
//        2、调用持久层，紧跟的第一个MyBatis查询语句被分页
        List<Comment> comments=commentMapper.queryByConditions(comment,time);//select查询语句将会被PageHelper拦截，添加上limit的操作
        for (Comment c:comments) {
            if (c.getSong()!=null){
                if (c.getSong().getAlbumId()!=null){
                   Album album= albumMapper.selectByPrimaryKey(c.getSong().getAlbumId());
                   c.getSong().setAlbum(album);
                }
                if (c.getSong().getGenresId()!=null){
                    Genres genres=genresMapper.queryById(c.getSong().getGenresId());
                    c.getSong().setGenres(genres);
                }
                if (c.getSong().getSingerId()!=null){
                    Singer singer=singerMapper.selectByPrimaryKey(c.getSong().getSingerId());
                    c.getSong().setSinger(singer);
                }
            }
        }

//        3、封装pageInfo
        PageInfo<Comment> pageInfo=new PageInfo<>(comments);
        return pageInfo;
    }

    @Override
    public boolean addComment(Comment comment) {
        return commentMapper.addComment(comment)>0;
    }

    @Override
    public int doCommentLike(CommentLike commentLike) {
        boolean flag=true;
        List<CommentLike> commentLikes=commentLikeMapper.queryByCommentId(commentLike.getCommentId());
        if (!commentLikes.isEmpty()){
        for (CommentLike like:commentLikes) {
            if (like.getUserId().equals(commentLike.getUserId())){
                flag=false;
            }
        }
        }
        if (flag){
            boolean f=commentLikeMapper.addCommentLike(commentLike)>0;
            if (f){
                return 1;
            }else{
                return  2 ;
            }
        }else{
            boolean f=commentLikeMapper.deleteCommentLike(commentLike)>0;
            if (f){
                return 0;
            }else{
                return  2 ;
            }
        }
    }


}
